//
//  MessageCell.m
//  Gabber
//
//  Created by 惠国 陆 on 11-10-11.
//  Copyright (c) 2011年 恒生聚源. All rights reserved.
//

#import "MessageCell.h"
#import "Message.h"
#import "XMPPClient.h"

@implementation MessageCell

@synthesize nameLabel=_nameLabel;
@synthesize timestampLabel=_timestampLabel;
//@synthesize contentLabel=_contentLabel;
@synthesize avatarView=_avatarView;
//@synthesize messageLabel=_messageLabel;
@synthesize badgeLabel=_badgeLabel;


@synthesize message=_message;
@synthesize badgeValue=_badgeValue;

static const NSInteger kMaxBadgeNumber = 99;
static const NSInteger  kMessageTextLineCount       = 1;
static const CGFloat    kDefaultMessageImageWidth   = 34.0f;
static const CGFloat    kDefaultMessageImageHeight  = 34.0f;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
//        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        self.accessoryView = self.badge;
        
        self.textLabel.font = TTSTYLEVAR(font);
        self.textLabel.textColor = TTSTYLEVAR(textColor);
        self.textLabel.highlightedTextColor = TTSTYLEVAR(highlightedTextColor);
        self.textLabel.backgroundColor = TTSTYLEVAR(backgroundTextColor);
        self.textLabel.textAlignment = UITextAlignmentLeft;
        self.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
        self.textLabel.adjustsFontSizeToFitWidth = YES;
        self.textLabel.contentMode = UIViewContentModeLeft;
        
        self.detailTextLabel.font = TTSTYLEVAR(font);
        self.detailTextLabel.textColor = TTSTYLEVAR(tableSubTextColor);
        self.detailTextLabel.highlightedTextColor = TTSTYLEVAR(highlightedTextColor);
        self.detailTextLabel.backgroundColor = TTSTYLEVAR(backgroundTextColor);
        self.detailTextLabel.textAlignment = UITextAlignmentLeft;
        self.detailTextLabel.contentMode = UIViewContentModeTop;
        self.detailTextLabel.lineBreakMode = UILineBreakModeTailTruncation;
        self.detailTextLabel.numberOfLines = kMessageTextLineCount;
        self.detailTextLabel.contentMode = UIViewContentModeLeft;
        
    }
    return self;
}

- (void)dealloc {
    
    
    TT_RELEASE_SAFELY(_avatarView);
    TT_RELEASE_SAFELY(_badgeLabel);  
    TT_RELEASE_SAFELY(_nameLabel);
    TT_RELEASE_SAFELY(_timestampLabel);
    //TT_RELEASE_SAFELY(_contentLabel);
    TT_RELEASE_SAFELY(_message);   
    TT_RELEASE_SAFELY(_badgeValue);   
    [super dealloc];
}

- (NSString*)formatMessageTimestamp:(NSDate *) timestamp;
{
    NSTimeInterval diff = -[timestamp timeIntervalSinceDate:[NSDate dateWithToday]];
    if (diff < 0) {
        return [NSDateFormatter localizedStringFromDate:timestamp dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
        
    } else {
        return [NSDateFormatter localizedStringFromDate:timestamp dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    }
    
}

- (UILabel*)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.textColor = [UIColor blackColor];
        _nameLabel.highlightedTextColor = [UIColor whiteColor];
        _nameLabel.font = TTSTYLEVAR(tableFont);
        _nameLabel.contentMode = UIViewContentModeLeft;
        [self.contentView addSubview:_nameLabel];
    }
    return _nameLabel;
}

- (UILabel*)timestampLabel {
    if (!_timestampLabel) {
        _timestampLabel = [[UILabel alloc] init];
        _timestampLabel.font = TTSTYLEVAR(tableTimestampFont);
        _timestampLabel.textColor = TTSTYLEVAR(timestampTextColor);
        _timestampLabel.highlightedTextColor = [UIColor whiteColor];
        _timestampLabel.contentMode = UIViewContentModeLeft;
        [self.contentView addSubview:_timestampLabel];
    }
    return _timestampLabel;
}

- (UIImageView*)avatarView {
    if (!_avatarView) {
        _avatarView = [[UIImageView alloc] init];
        [self.contentView addSubview:_avatarView];
    }
    return _avatarView;
}
//-(TTStyledTextLabel*) messageLabel {
//    if (!_messageLabel) {
//        _messageLabel = [[TTStyledTextLabel alloc] init];
//        [self.contentView addSubview:_messageLabel];
//    }
//    return _messageLabel;    
//    
//}

- (TTLabel*)badge {
    if (_badgeLabel == nil) {
        _badgeLabel = [[TTLabel alloc] init];
        _badgeLabel.style = TTSTYLE(badge);
        _badgeLabel.backgroundColor = [UIColor clearColor];
        _badgeLabel.userInteractionEnabled = NO;
        //[self.contentView addSubview:_badge];
    }
    return _badgeLabel;
}



- (void)updateBadge {
    
    
    NSString *badgeText = nil;
    
    
    if (_badgeValue != nil) {
        NSRange range = [_badgeValue rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet]
                                                              invertedSet]];
        
        if (range.location == NSNotFound && [self.badgeValue integerValue] > kMaxBadgeNumber) {
            badgeText = [NSString stringWithFormat:@"%d+", kMaxBadgeNumber];
            
        } else {
            badgeText = _badgeValue;
        }
    }
    
    _badgeLabel.text = badgeText;
    _badgeLabel.hidden = _badgeValue == nil;
    [_badgeLabel sizeToFit];
    //[self setNeedsLayout];
}


- (void)layoutSubviews {
    [super layoutSubviews];

   
    CGFloat left = 0.0f;
    if (_avatarView) {
        _avatarView.frame = CGRectMake(kTableCellSmallMargin, kTableCellSmallMargin,
                                       kDefaultMessageImageWidth, kDefaultMessageImageHeight);
        left += kTableCellSmallMargin + kDefaultMessageImageHeight + kTableCellSmallMargin;
        
    } else {
        left = kTableCellMargin;
    }
    
    
    CGFloat width = self.contentView.width - left;
    CGFloat top = floor((self.contentView.height - (_nameLabel.font.ttLineHeight + self.detailTextLabel.font.ttLineHeight))/2);//kTableCellSmallMargin;
    
    if (_nameLabel.text.length) {
        _nameLabel.frame = CGRectMake(left, top, width, _nameLabel.font.ttLineHeight);
        top += _nameLabel.height;
        
    } else {
        _nameLabel.frame = CGRectZero;
    }
    
    
    if (self.detailTextLabel.text.length) {
        CGFloat textHeight = self.detailTextLabel.font.ttLineHeight * kMessageTextLineCount;
        self.detailTextLabel.frame = CGRectMake(left, top, width, textHeight);
        
    } else {
        self.detailTextLabel.frame = CGRectZero;
    }
    
    if (_timestampLabel.text.length) {
        _timestampLabel.alpha = !self.showingDeleteConfirmation;
        [_timestampLabel sizeToFit];
        _timestampLabel.left = self.contentView.width - (_timestampLabel.width + kTableCellSmallMargin);
        _timestampLabel.top = _nameLabel.top;
        _nameLabel.width -= _timestampLabel.width + kTableCellSmallMargin*2;
        
    } else {
        _timestampLabel.frame = CGRectZero;
    }

    
}

- (void)setBadgeValue:(NSString *)badgeValue 
{
    [_badgeValue release];
    _badgeValue = [badgeValue copy];
    
    [self updateBadge];
    
}    

- (void)setMessage:(Message *)message {
    if (_message != message) {
        [_message release];
        _message = [message retain];
        if (message) {
            @try {
                XMPPUserCoreDataStorageObject* user = [[XMPPClient sharedInstance] userForJID:[XMPPJID jidWithString: message.jidStr]];
                

                self.avatarView.image = [[XMPPClient sharedInstance] avatarForUser:user];
                
                
                if (user.displayName.length) {
                    self.nameLabel.text = user.displayName;
                }
                if (message.content.length) {
                    self.detailTextLabel.text = message.content;
                }
                if (message.timestamp) {
                    self.timestampLabel.text = [message.timestamp formatShortTime];
                }
            }
            @catch (NSException *exception) {
                DDLogWarn(@"Exception: %@", exception);
            }
            @finally {
                
            }
            
        }
        
    }
}



- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (void)prepareForReuse
{
    self.message = nil;
    self.badgeValue = nil;
    
    self.avatarView.image = nil;
    self.nameLabel.text = nil;
    self.timestampLabel.text = nil;
    self.detailTextLabel.text = nil;
    
    self.badge.text = nil;
    [super prepareForReuse];
    
    
}

@end
